/**
 * Administrator
 * 2011-3-17
 * TODO
 */
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**联合航空分析
 * @author 0707
 * @date 2011-3-17
 * @description TODO
 */
public class GetFlightListKN {


	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "et.cu-air.com");
		    header.put("Referer", "http://et.cu-air.com/knair/b2cnew/index_right.jsp");
 
			//使用POST请求，赋值post数据
			postData.put("Adult", "1");  
			postData.put("departure", queryInfo.getOrgCity());  //出发机场
			postData.put("arrival", queryInfo.getDesCity());  //到达机场
			postData.put("takeoffDate", queryInfo.getDateString());  //出发日期
			postData.put("travelType","0");   
			postData.put("Child", "0");   
			postData.put("airline", "KN");    //0:单程  1:往返 
			postData.put("radom", "963749");  
			 
 
	        try {
	        	//返回的HTML
				responseText = proxy.doRequest(
		 	    "http://et.cu-air.com/knair/queryAvnew.do", postData, header,"GBK");
				 resultInfo = (ResultInfo)analyzeResopnseText(responseText);
	            
			}catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
	        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
	
	          	return resultInfo;
			 
		}
		
		
		/**
		 * 根据山东航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象

		      if (source==null||source.trim().length()==0) {
				return null;
			}
	 		  String[] parts = source.split("<tr class=\"flight_tab_con_seg\">"); //将每一个航班区分开来
			  
	 		  if (parts.length==0) {     //没有航班信息
				System.out.println("联合航空没有相应航班信息------------------------------");
				return null;
			}
 
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			     regexSB.append("<td height=\"50px\"><img src=\"b2cnew/image/airline_logo.gif\"\\s*/></td>"); 
			     regexSB.append("\\s*<td>(.*?)</td>\\s*");  //航班号
			      regexSB.append("<td>(.*?)-(.*?)</td>\\s*");//起飞时间&降落时间
			      regexSB.append("<td>(.*?)</td>\\s*");  //机型
			      regexSB.append("<td>(.*?)</td>");  //是否经停（经停、直达）
			     
			     //航班号  ，航班号+代码共享 ，出发时间，降落时间。
			     String regex =regexSB.toString();
			     String priceRegex = "";

			     priceRegex = "<tr\\s*id=\"planego\\d{1,3}\"\\s*class=\"flight_tab_con_more\"\\s*style=\"display:none\">\\s*<td\\s*>\\s*</td>\\s*<td colspan=\"8\"\\s*>(.*?)</td>";
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
			     Pattern pPrice = Pattern.compile(priceRegex,Pattern.CASE_INSENSITIVE);

			     FlightInfo tempInfo = null;
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
 
			     //依次取出每个航班的信息,因为parts[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 		      
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
			     Matcher matcher = p.matcher(parts[j]);
			     if(matcher.find())   //匹配航班信息
			     {	    	 
 
			    	 String flightNo = matcher.group(1).trim();
			    	 String stopOverString = matcher.group(5).trim();
			    	 tempInfo.setFlightNo(flightNo);
         	    	 tempInfo.setTakeOffTime(matcher.group(2).trim());
			    	 tempInfo.setArriveTime(matcher.group(3).trim());
			    	 tempInfo.setPlaneType(matcher.group(4).trim());
			    	 if (stopOverString!=null&&stopOverString.equals("经停")) {
			    		 tempInfo.setStopOver(true);
					}
			     }
			    	 //分析价格start
			    	 Matcher mPrice = pPrice.matcher(parts[j]);
 
			    	if (mPrice.find()) {
				    	 double tempMinPrice = 0.0;
				    	 double tempMaxPrice = 0.0;
				    	 boolean isFirst = true;
						String priceSource = mPrice.group(1).trim();	//需要在这个字符串中匹配该航班的价格信息	    		
                       
						if (priceSource==null||priceSource.length()==0) {
                    	   System.out.println("联合航空，价格为空");
						    return null;
					}
						
						String regexPrice   =  "<p><span>.*?</span><br\\s*/><input\\s*type=radio\\s*name='\\d{1}_\\d{1}'\\s*value='(.*?)'\\s*onclick='checktkt\\(this,\".*?\",\".*?\"\\)' />￥(.*?)<br\\s*/>\\s*<span class='seatNum'>";
			    	                        	 
						
						Pattern patternPrice =  Pattern.compile(regexPrice);
			    		Matcher matcherPrice = patternPrice.matcher(priceSource);
			    		boolean haveSeat = false;
			    		
			    		while(matcherPrice.find()){
			    			priceInfo  = new PriceInfo();
			    			haveSeat = true;        //如果找到该格式，则说明舱位都可以订票
			    			String cabin = matcherPrice.group(1).split(",")[9];
			    			
			    	 
			    			double price = Double.parseDouble(matcherPrice.group(2).trim());
			    			priceInfo.setSpace(cabin.trim());
			    			priceInfo.setPrice(price);
			    		    priceInfo.setRemind(getRemidByCabin(cabin.trim()));
			    			priceList.add(priceInfo);
			    			  if (isFirst) {
					    		  tempMinPrice = priceInfo.getPrice();
					    		  tempMaxPrice = priceInfo.getPrice();
					    		  tempInfo.setMinprice(tempMinPrice);
					    		  tempInfo.setMaxprice(tempMaxPrice);
					    		  isFirst = false;
							}
					    	 
							     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
							    	 tempMinPrice = priceInfo.getPrice();
									}
							     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
							    	 tempMaxPrice = priceInfo.getPrice(); 
								}
							     tempInfo.setMaxprice(tempMaxPrice);
							     tempInfo.setMinprice(tempMinPrice);
			    		}
			    		//开始分析么有座位的情况
			    		if (haveSeat==false) {
			    	 
							tempInfo.setHaveSeat(false);
							String regexPriceInvalid = "<p>\\s*<span class='seatNum'>(.*?)<BR>\\d{1,3}</span><BR>￥(.*?)</p>";
							
							Pattern patternPriceInvalid = Pattern.compile(regexPriceInvalid);
							Matcher matcherPriceInvalid = patternPriceInvalid.matcher(priceSource);
							
							while (matcherPriceInvalid.find()) {
							 priceInfo = new PriceInfo();
							 String cabin  = getCabinByDescripbe(matcherPriceInvalid.group(1).trim());		 
							 priceInfo.setPrice(Double.parseDouble(matcherPriceInvalid.group(2).trim()));
							 priceInfo.setSpace(cabin);
							 priceInfo.setRemind(getRemidByCabin(cabin.trim()));	
							 priceList.add(priceInfo);
							  if (isFirst) {
					    		  tempMinPrice = priceInfo.getPrice();
					    		  tempMaxPrice = priceInfo.getPrice();
					    		  tempInfo.setMinprice(tempMinPrice);
					    		  tempInfo.setMaxprice(tempMaxPrice);
					    		  isFirst = false;
							}
					    	 
							     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
							    	 tempMinPrice = priceInfo.getPrice();
									}
							     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
							    	 tempMaxPrice = priceInfo.getPrice(); 
								}
							     tempInfo.setMaxprice(tempMaxPrice);
							     tempInfo.setMinprice(tempMinPrice);
							}
						
						}
			    		
			    		tempInfo.setPrice(priceList);
					}
			    	flightInfos.add(tempInfo);
			    	 //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
				     if (tempIsFirstForAll) {      //初始值
				    	 tempMinPriceForAll = tempInfo.getMinprice();
				    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				    	 tempIsFirstForAll  = false;
					}
				     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
	 
				    	 tempMinPriceForAll = tempInfo.getMinprice();
					}
				     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
					 
				    	 tempMaxPriceForAll = tempInfo.getMaxprice();
					}
			    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
			    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
 		     	 }
 		    resultInfo.setResultList(flightInfos);	  
 		 	 
			return resultInfo;
		}

/**
 * 根据舱位名称得到舱位代码	
 * 取自联航的舱位优惠说明
 * @return
 */
public String getCabinByDescripbe(String cabinDesc) {
	String cabinCode = "";
	if (cabinDesc==null||cabinDesc.length()==0) {
		return "";
	}
	if (cabinDesc.indexOf("头等舱")>=0) {
		cabinCode = "F";
	}
	
	if (cabinDesc.indexOf("商务舱")>=0) {
		cabinCode = "C";
	}
	if (cabinDesc.indexOf("经济舱全价")>=0 ) {
		cabinCode = "Y";
	}
	if (cabinDesc.indexOf("经济舱90折")>=0 ) {
		cabinCode = "B";
	}	if (cabinDesc.indexOf("经济舱85折")>=0 ) {
		cabinCode = "E";
	}	if (cabinDesc.indexOf("经济舱80折")>=0 ) {
		cabinCode = "H";
	}	if (cabinDesc.indexOf("经济舱75折")>=0 ) {
		cabinCode = "L";
	}	if (cabinDesc.indexOf("经济舱70折")>=0 ) {
		cabinCode = "M";
	}	if (cabinDesc.indexOf("经济舱65折")>=0 ) {
		cabinCode = "N";
	}	if (cabinDesc.indexOf("经济舱60折")>=0 ) {
		cabinCode = "R";
	}	if (cabinDesc.indexOf("经济舱55折")>=0 ) {
		cabinCode = "S";
	}	if (cabinDesc.indexOf("经济舱50折")>=0 ) {
		cabinCode = "V";
	}if (cabinDesc.indexOf("经济舱45折")>=0 ) {
		cabinCode = "T";
	}if (cabinDesc.indexOf("经济舱40折")>=0 ) {
		cabinCode = "W";
	}
	if (cabinDesc.indexOf("经济舱35折")>=0 ) {
		cabinCode = "G";
	}
	//Y:100、G:35、F:180、E:85、B:90、H:80、L:75、M:70、N:65、R:60、S:55、V:50、T:45、W:40、C:200
	
	return cabinCode;
}		
		
		
		
/**
 * 根据舱位获取退改签信息
 * @return
 */
public String  getRemidByCabin(String cabin) {
	String remind  = "";
	if (cabin==null||cabin.length()==0) {
		return "";
	}
 if (cabin.equals("Y")) {
	 remind = "允许签转，允许变更";
}
 if(cabin.equals("G")){
	 remind = "不得签转退票变更";
}
 if(cabin.equals("F")){
	 remind = "允许签转，允许变更";
}
 if(cabin.equals("X")){
	 remind = "不得签转变更退票费80%";
}
 if(cabin.equals("E")){
	 remind = "不得签转";
}
 //B,H,L,M,N,R,S,V,T,W,Q,C"
 if(cabin.equals("B")){
	 remind = "不得签转";
}
 if(cabin.equals("H")){
	 remind = "不得签转";
}
 if(cabin.equals("L")){
	 remind = "不得签转";
}
 if(cabin.equals("M")){
	 remind = "不得签转";
}
 if(cabin.equals("N")){
	 remind = "不得签转";
}
 if(cabin.equals("R")){
	 remind = "不得签转";
}
 if(cabin.equals("S")){
	 remind = "不得签转";
}
 if(cabin.equals("V")){
	 remind = "不得签转";
}
 if(cabin.equals("T")){
	 remind = "不得签转";
}
 if(cabin.equals("W")){
	 remind = "不得签转";
}
 if(cabin.equals("Q")){
	 remind = "不得签转变更退票";
}
 if(cabin.equals("C")){
	 remind = "允许签转，允许变更";
}
 return remind;
}

}
